package com.gamemost.templestay;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Locale;

import org.xmlpull.v1.XmlPullParserException;

import android.R.integer;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.Window;
import android.widget.RelativeLayout;

import com.gamemost.dao.BookDatasource;
import com.gamemost.dao.MySQLiteHelper;
import com.gamemost.dao.ResourceDatasource;
import com.gamemost.dao.XMLProvider;
import com.gamemost.entity.BookRecent;
import com.gamemost.entity.BookStand;
import com.gamemost.entity.DownloadedBook;
import com.gamemost.entity.JSONParser;
import com.gamemost.entity.SubCategory;
import com.gamemost.layout.LayoutGridBook;
import com.gamemost.layout.LayoutMainScreen;
import com.gamemost.layout.LayoutViewReadBook;
import com.gamemost.managers.BookManager;
import com.gamemost.managers.LayoutManager;
import com.gamemost.managers.ResourcesManager;
import com.gamemost.templestay.R;

public class MainActivity extends Activity {
	private RelativeLayout rlMain;
	public BookManager bookManager;
	// public
	public String url = "http://14.63.197.31:8080/templestay/getBooksByUserStatusLimit?user_id=8807f6e7-4380-4627-9168-d7057dad3a21&status_id=6&offset=0&length=10";
	public String urlBookStand = "http://14.63.197.31:8080/templestay/getUserFoldersLimit?user_id=8807f6e7-4380-4627-9168-d7057dad3a21&offset=0&length=10";
	public String urlListBookInBookStand = "http://14.63.197.31:8080/templestay/getFolderBooksLimit?folder_id=500e576dbab7-4314-b928-e7f40901c540&offset=0&length=10";
	public String urlSubCategory = "";
	public String urlListBookSubCategory = "";
	public ArrayList<BookRecent> listBookRecent = new ArrayList<BookRecent>();
	public ArrayList<BookRecent> listBookDownloaded = new ArrayList<BookRecent>();
	public ArrayList<BookStand> listBookStand = new ArrayList<BookStand>();
	public ArrayList<BookRecent> listBookSubCategory = new ArrayList<BookRecent>();
	public ArrayList<BookRecent> listBookInListBookStand = new ArrayList<BookRecent>();
	public ArrayList<DownloadedBook> listDownloadedBook = new ArrayList<DownloadedBook>();
	public ArrayList<DownloadedBook> listDownloadedBookInListBookStand = new ArrayList<DownloadedBook>();
	public ArrayList<String> listStringSubCategory = new ArrayList<String>();
	public ArrayList<SubCategory> listSubCategory = new ArrayList<SubCategory>();
	public ProgressDialog waitDialog;
	public int firtcount1,firtcount2 ;

	// that
	public void setURLListSubCategory(String folder_id) {
		this.urlSubCategory = "http://14.63.197.31:8080/templestay/getCustomCategoryList?folder_id="
				+ folder_id;
	}

	public void setURLBookNew(int offset, int lenght) {
		this.url = "http://14.63.197.31:8080/templestay/getBooksByUserStatusLimit?user_id=8807f6e7-4380-4627-9168-d7057dad3a21&status_id=6&offset="
				+ offset + "&length=" + lenght;
	}

	public void setURLBookStand(int offset, int lenght) {
		this.urlBookStand = "http://14.63.197.31:8080/templestay/getUserFoldersLimit?user_id=8807f6e7-4380-4627-9168-d7057dad3a21&offset="
				+ offset + "&length=" + lenght;
	}

	public void setURLListBookInBookStand(int offset, int lenght,
			String folder_id) {
		this.urlListBookInBookStand = "http://14.63.197.31:8080/templestay/getFolderBooksLimit?folder_id="
				+ folder_id + "&offset=" + offset + "&length=" + lenght;
	}

	public void setURLListBookSubCategory(String custcat_id, int offset,
			int length) {
		this.urlListBookSubCategory = "http://14.63.197.31:8080/templestay/getBookFromCustomCategory?custcat_id="
				+ custcat_id + "&offset=" + offset + "&length=" + length;
	}

	// test
//	 public void setURLListSubCategory(String folder_id) {
//	 //
//	 http://14.63.217.106:8088/test/getCustomCategoryList?folder_id=h915472e-cwr7-4913-ab8e-d8bc309ab4f2
//	 this.urlSubCategory =
//	 "http://14.63.217.106:8088/test/getCustomCategoryList?folder_id="
//	 + folder_id;
//	 }	 
//	 public void setURLBookNew(int offset, int lenght) {
//	 //
//	 http://14.63.217.106:8088/test/getBooksByUserStatusLimit?user_id=3653f552-aebe-49f8-969f-35a34dca3f88&status_id=6&offset=0&length=10
//	 this.url =
//	 "http://14.63.217.106:8088/test/getBooksByUserStatusLimit?user_id=3653f552-aebe-49f8-969f-35a34dca3f88&status_id=6&offset="
//	 + offset + "&length=" + lenght;
//	 }
//	
//	 public void setURLBookStand(int offset, int lenght) {
//	 this.urlBookStand =
//	 "http://14.63.217.106:8088/test/getUserFoldersLimit?user_id=3653f552-3f88&offset="
//	 + offset + "&length=" + lenght;
//	 }
//	
//	 public void setURLListBookInBookStand(int offset, int lenght,
//	 String folder_id) {
////	  http://14.63.217.106:8088/test/getFolderBooksLimit?
////	 folder_id=h915472e-cwr7-4913-ab8e-d8bc309ab4f2&offset=0&length=10
//	 this.urlListBookInBookStand =
//	 "http://14.63.217.106:8088/test/getFolderBooksLimit?folder_id="
//	 + folder_id + "&offset=" + offset + "&length=" + lenght;
//	 }
//	
//	 public void setURLListBookSubCategory(String custcat_id, int offset,
//	 int length) {
//	 //
//	 http://14.63.217.106:8088/test/getBookFromCustomCategory?custcat_id=3ad630a5-858f-42ee-8731-dc783f4a049e&offset=0&length=10
//	 this.urlListBookSubCategory =
//	 "http://14.63.217.106:8088/test/getBookFromCustomCategory?custcat_id="
//	 + custcat_id + "&offset=" + offset + "&length=" + length;
//	 }

	public int width = 720;
	public int height = 1280;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_main);
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		rlMain = (RelativeLayout) findViewById(R.id.main_layout);
		ResourcesManager.getInstance().preManager(this);
		DisplayMetrics dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);
		Config.initFolder();
		ResourceDatasource.copyResourceFiles(getBaseContext());
		MySQLiteHelper.getInstance(getBaseContext());
		listDownloadedBook = BookDatasource.getInstance(getBaseContext())
				.getListBook(0);
		width = dm.widthPixels;
		height = dm.heightPixels;		
		bookManager = new BookManager();
		waitDialog = new ProgressDialog(this);
		waitDialog.setMessage(getResources().getString(R.string.loading)
				+ "...");
		waitDialog.setCancelable(false);
		waitDialog.show();
		firtcount1 = 0;
		firtcount2 = 0;
		addBookFromDB(listBookRecent);
		if (isOnline()) {
			new LoadSeviceBookTask().execute(new String[] { url, urlBookStand,
					"", "", "" });
		} else {
			showDialoNotConnected();
			onLoadDataLocal();
		}

		version = Build.VERSION.RELEASE;
		System.out.println("version " + version);
		if (version.contains("4.2")) {
			ImageServer imageServer = new ImageServer("127.0.0.1",
					getBaseContext());
			try {
				imageServer.start();
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();

			}
		}
	}

	public void onLoadDataLocal() {
		// TODO Auto-generated method stub		
		try {
			XMLProvider.parseRecentXml(listBookRecent);
			XMLProvider.parseStandXml(listBookStand);
		} catch (XmlPullParserException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// checkDuplicate();
		LayoutMainScreen.getInstance().onCreate();
		LayoutMainScreen.getInstance().mAdapterNewBook
				.setListNewBook(listBookRecent);
		LayoutMainScreen.getInstance().mAdapterNewBook.notifyDataSetChanged();
		LayoutMainScreen.getInstance().mAdapterBookStand
				.setListNewBook(listBookStand);
		LayoutMainScreen.getInstance().mAdapterBookStand.notifyDataSetChanged();
		ResourcesManager.ac.waitDialog.hide();
		updateTexts();
	}

	public String version;

	public ArrayList<BookRecent> getBookHasDownLoad() {
		ArrayList<BookRecent> list = new ArrayList<BookRecent>();
		if (!listBookRecent.isEmpty()) {
			for (int i = 0; i < listBookRecent.size(); i++) {
				if (listBookRecent.get(i).hasDownload) {
					BookRecent clone;
					try {
						clone = (BookRecent) listBookRecent.get(i).clone();
						clone.setBitmap(Bitmap.createScaledBitmap(
								clone.getBitmap(), width / 5, height / 6, true));
						list.add(clone);
					} catch (CloneNotSupportedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

				}
			}
		}
		return list;
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		// TODO Auto-generated method stub
		if (LayoutViewReadBook.getInstance() != null
				&& LayoutManager.getInstance().getCurrentLayout() != null) {
			if (LayoutManager.getInstance().getCurrentLayout()
					.equals(LayoutViewReadBook.getInstance())) {
				LayoutViewReadBook.getInstance().orienChange = true;
				LayoutViewReadBook.getInstance().loadAfterOrienchange = false;
				if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
					LayoutViewReadBook.getInstance().reload();

				} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
					LayoutViewReadBook.getInstance().reload();
				}
			}

		}
		if (LayoutMainScreen.getInstance() != null
				&& LayoutManager.getInstance().getCurrentLayout() != null) {
			if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE
					&& LayoutViewReadBook.getInstance().isback) {

				LayoutMainScreen.getInstance().onCreate();
			}
			if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT
					&& LayoutViewReadBook.getInstance().isback) {
				LayoutMainScreen.getInstance().onCreate();
			}
		}
		updateTexts();
		super.onConfigurationChanged(newConfig);
	}

	public void addBookFromDB(ArrayList<BookRecent> list) {
		// TODO Auto-generated method stub
		if (!listDownloadedBook.isEmpty()) {
			for (int i = 0; i < listDownloadedBook.size(); i++) {
				BookRecent br = new BookRecent();
				br.hasDownload = true;
				br.setFilename(listDownloadedBook.get(i).getFilename());
				br.setId(listDownloadedBook.get(i).getId());
				br.setImage(listDownloadedBook.get(i).getImage());
				br.setTypeBook(listDownloadedBook.get(i).getTypeBook());
				if (br.getTypeBook() == Config.FIX_LAYOUT) {
				br.setBookmark(listDownloadedBook.get(i).getBookmarkString());
				} else {
					System.out.println("aaaaaaaaaaaaaaaaaa addBookFromDB");
					br.setBookmark(listDownloadedBook.get(i).getStringBMReflow());
				}
				br.setBookcover(listDownloadedBook.get(i).getBookcover());
				br.setCategoryId(listDownloadedBook.get(i).getCategoryId());
				br.setTitle(listDownloadedBook.get(i).getTitle());
				br.setUrl(listDownloadedBook.get(i).getUrl());
				String imagePath = Environment.getExternalStorageDirectory()
						.toString() + Config.IMAGE_BOOK + "/" + br.getImage();
				File f = new File(imagePath);
				Bitmap bitmap = DownloadImageService.decodeFile(f);
				Bitmap bmp = Bitmap.createScaledBitmap(bitmap,
						2 * ResourcesManager.ac.width / 7,
						ResourcesManager.ac.height / 4, true);
				if (bitmap == null) {
					Drawable drawable = getResources().getDrawable(
							R.drawable.no_book_cover);
					if (drawable instanceof BitmapDrawable) {
						listBookDownloaded
								.get(i)
								.setBitmap(
										Bitmap.createScaledBitmap(
												((BitmapDrawable) drawable)
														.getBitmap(),
												2 * ResourcesManager.ac.width / 7,
												ResourcesManager.ac.height / 4,
												true));
					}
				}
				br.setBitmap(bmp);
				listBookDownloaded.add(br);
			}
			addBookDownload(list);
		}
	}

	public int getPosMinNotBookDownload(ArrayList<BookRecent> list) {
		if (!list.isEmpty()) {
			for (int i = 0; i < list.size(); i++) {
				if (!list.get(i).isHasDownload()) {
					return i;
				}
			}
		}
		return -1;
	}

	public void showDialogFullList() {
		AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
		alertDialogBuilder.setTitle("List Book ");
		alertDialogBuilder
				.setMessage("This list is full please del some book  ...");
		alertDialogBuilder.setPositiveButton("OK",
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						dialog.cancel();
						LayoutMainScreen.loadingEndItem = false;
					}
				});
		AlertDialog ad = alertDialogBuilder.create();
		ad.show();
	}

	public String tt_connection, m_disconnection, tt_book, m_load, m_openbook,
			m_delete, tt_yes, tt_cancel, m_downloadbook, tt_category, m_back,
			m_white, m_yellowmilk, tt_service, m_service, m_notdownload,
			toas_longclick, toast_addbookmark, toast_delbookmark, m_category,
			tt_index, tt_bookmark;

	public void changeLang(String lang) {
		// TODO Auto-generated method stub
		System.out.println("lang is " + lang);
		if (lang.equalsIgnoreCase(""))
			return;
		Locale myLocale = new Locale(lang);
		Locale.setDefault(myLocale);
		android.content.res.Configuration config = new android.content.res.Configuration();
		config.locale = myLocale;
		getBaseContext().getResources().updateConfiguration(config,
				getBaseContext().getResources().getDisplayMetrics());
	}

	public void updateTexts() {
		System.out.println("updateText "+Config.lang);
		if (Config.lang == 0) {
			
			changeLang("en");
		} else {
			changeLang("kr");
		}
		LayoutMainScreen.getInstance().updateText();
		tt_connection = getResources().getString(R.string.t_connection);
		m_disconnection = getResources().getString(R.string.connection);
		tt_book = getResources().getString(R.string.book);
		m_openbook = getResources().getString(R.string.openbook);
		m_load = getResources().getString(R.string.loading);
		tt_yes = getResources().getString(R.string.yes);
		tt_cancel = getResources().getString(R.string.cancel);
		m_downloadbook = getResources().getString(R.string.downbook);
		m_delete = getResources().getString(R.string.delete);
		tt_category = getResources().getString(R.string.category);
		m_category = getResources().getString(R.string.m_category);
		m_back = getResources().getString(R.string.black);
		m_white = getResources().getString(R.string.white);
		m_yellowmilk = getResources().getString(R.string.yellowmilk);
		tt_service = getResources().getString(R.string.service);
		m_service = getResources().getString(R.string.servive_m);
		m_notdownload = getResources().getString(R.string.m_notdownload);
		toas_longclick = getResources().getString(R.string.toast_longclick);
		toast_addbookmark = getResources().getString(R.string.toast_addbookmar);
		toast_delbookmark = getResources().getString(R.string.toast_delbookmar);
		tt_index = getResources().getString(R.string.index);
		tt_bookmark = getResources().getString(R.string.bookmark);
	}

	public void removeBooknew(ArrayList<BookRecent> list, BookRecent br) {
		if (!list.isEmpty()) {
			for (int i = 0; i < list.size(); i++) {
				System.out.println(br.getId() + "==" + list.get(i).getId());
				if (br.getId().equals(list.get(i).getId())) {
					list.remove(i);
					System.out.println(" da remo khoi list============");
					break;
				}
			}
		}
	}

	public void removeBookDownload(ArrayList<DownloadedBook> list, BookRecent br) {
		if (!list.isEmpty()) {
			for (int i = 0; i < list.size(); i++) {
				if (br.getId().equals(list.get(i).getId())) {
					list.remove(i);
					break;
				}
			}
		}
	}

	public void showDialoNotConnected() {
		AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
		alertDialogBuilder.setTitle(tt_connection);
		alertDialogBuilder.setMessage(m_disconnection);
		alertDialogBuilder.setPositiveButton(tt_yes,
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						dialog.cancel();
						LayoutMainScreen.loadingEndItem = false;
					}
				});
		AlertDialog ad = alertDialogBuilder.create();
		ad.show();
	}

	public boolean isOnline() {
		ConnectivityManager connectivity = (ConnectivityManager) this
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo[] info = connectivity.getAllNetworkInfo();
		if (info != null)
			for (int i = 0; i < info.length; i++)
				if (info[i].getState() == NetworkInfo.State.CONNECTED) {
//					boolean b = executeCammand();
//					
//					System.out.println("isboolean "+b);
					return true;
				}
		return false;
	}
	private boolean executeCammand(){
        System.out.println(" executeCammand");
        Runtime runtime = Runtime.getRuntime();
        try
        {
            Process  mIpAddrProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
            int mExitValue = mIpAddrProcess.waitFor();
            System.out.println(" mExitValue "+mExitValue);
            if(mExitValue==0){
                return true;
            }else{
                return false;
            }
        }
        catch (InterruptedException ignore)
        {
            ignore.printStackTrace();
            System.out.println(" Exception:"+ignore);
        } 
        catch (IOException e) 
        {
            e.printStackTrace();
            System.out.println(" Exception:"+e);
        }
        return false;
    }
	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		Config.saveCacheToPref();
		super.onStop();
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		Config.saveCacheToPref();
		super.onPause();
	}

	public void addBookDownload(ArrayList<BookRecent> list) {
		// TODO Auto-generated method stub
		if (!listBookDownloaded.isEmpty()) {
			for (int i = 0; i < listBookDownloaded.size(); i++) {
				list.add(listBookDownloaded.get(i));
			}
		}
	}

	public void showDialogDownLoadBook() {
		AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
		alertDialogBuilder.setTitle(tt_book);
		alertDialogBuilder.setMessage(m_load);
		alertDialogBuilder.setPositiveButton(tt_yes,
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						dialog.cancel();
					}
				});
		AlertDialog ad = alertDialogBuilder.create();
		ad.show();
	}

	public void showDialogDelete(final int postion,
			final ArrayList<BookRecent> list, final int typelocation) {
		AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
		alertDialogBuilder.setTitle(tt_book);
		alertDialogBuilder.setMessage(m_delete);
		alertDialogBuilder.setPositiveButton(tt_yes,
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						if (typelocation == 0) {
							BookRecent br = list.get(postion);
							br.setHasDownload(false);
							int post = getPostionBookDownloaded(br,
									listDownloadedBook);
							if (post != -1) {
								BookDatasource.getInstance(ResourcesManager.ac)
										.deleteBook(
												listDownloadedBook.get(post));
								Config.unregisToCache(listDownloadedBook.get(
										post).getId());
								listDownloadedBook.remove(post);
								list.remove(postion);
								list.add(br);
								System.out.println(listBookRecent.size()
										+ " sizzzzzzzzzzzzzzzz");
								for (int i = 0; i < listBookRecent.size(); i++) {
									System.out.println(listBookRecent.get(i)
											.get(BookRecent.TAG_BOOK_ID)
											+ " == " + i);
								}
								LayoutMainScreen.getInstance().mAdapterNewBook
										.setListNewBook(listBookRecent);
								LayoutMainScreen.getInstance().mAdapterNewBook
										.notifyDataSetChanged();

							}
						}
						
					}
				});
		alertDialogBuilder.setNegativeButton(tt_cancel,
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						dialog.cancel();
					}
				});
		AlertDialog ad = alertDialogBuilder.create();
		ad.show();
	}

	public int getPostionBookDownloaded(BookRecent book,
			ArrayList<DownloadedBook> list) {
		if (!list.isEmpty()) {
			for (int i = 0; i < list.size(); i++) {
				if (list.get(i).getId().equals(book.getId())) {
					return i;
				}
			}
		}
		return -1;
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		if (waitDialog != null && waitDialog.isShowing()) {
			waitDialog.cancel();
		}
		Config.saveCacheToPref();
		System.exit(0);
	}

	public static int sizeListbookInBookStand = 0;

	public class LoadSeviceBookTask extends AsyncTask<String, String, String[]> {
		public int size, sizebookstand;
		public boolean isGetListBookRecent = false,isListBookStand = false,isGetListBookStand = false,isGetListSubCategory  = false,isGetListBookSubCategory = false;
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			size = listBookRecent.size();
			sizebookstand = listBookStand.size();
			waitDialog.show();
			super.onPreExecute();
		}

		@Override
		protected String[] doInBackground(String... params) {
			// TODO Auto-generated method stub
			JSONParser jParser = new JSONParser();
			if (!params[0].equals("")) {
				isGetListBookRecent = jParser.getListBookRecent(params[0], listBookRecent, 0);
			}
			if (!params[1].equals("")) {
				System.out.println("getListBookStand mainactivity");
				isListBookStand = jParser.getListBookStand(params[1], listBookStand);
			}
			if (!params[2].equals("")) {
				isGetListBookStand = jParser.getListBookRecent(params[2], listBookInListBookStand, 1);
			}

			if (!params[3].equals("")) {
				isGetListSubCategory = jParser.getListSubCategory(params[3], listSubCategory);
			}

			if (!params[4].equals("")) {
				isGetListBookSubCategory = jParser.getLIstBookSubCategory(params[4], listBookSubCategory);
			}
			
			return params;
		}

		@Override
		protected void onPostExecute(String[] result) {
			// TODO Auto-generated method stub
			// waitDialog.hide();
			super.onPostExecute(result);
			if (LayoutMainScreen.loadingEndItem)
				LayoutMainScreen.loadingEndItem = false;
			// thread download image
			if (!result[0].equals("")) {
				System.out.println("aaaaaaa " + listBookRecent.size());
				if (listBookRecent.size() > size) {
					String[] arrUrl = new String[listBookRecent.size() - size];
					for (int i = 0; i < listBookRecent.size() - size; i++) {
						System.out.println("");
						BookRecent aBook = listBookRecent.get(i + size);
						String ur = aBook.get(BookRecent.TAG_BOOK_COVER);
						String httpepub = aBook.get(BookRecent.TAG_BOOK_URL);
						if (httpepub != null && !httpepub.equals("")
								&& httpepub.contains("http:")) {
							arrUrl[i] = ur;
						}

					}
					DownloadImageService downImage = new DownloadImageService(0);
					downImage.setSize(size);
					downImage.execute(arrUrl);
				} else if(!isOnline() || !isGetListBookRecent && firtcount1 == 0){
					System.out.println("no network");
					if (!listBookRecent.isEmpty() ) {
						listBookRecent.clear();
					}	
					if (!listBookDownloaded.isEmpty()) {
						listBookDownloaded.clear();
					}
					addBookFromDB(listBookRecent);
					try {
						XMLProvider.parseRecentXml(listBookRecent);
					} catch (XmlPullParserException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					LayoutMainScreen.getInstance().onCreate();									
					LayoutMainScreen.getInstance().mAdapterNewBook
							.setListNewBook(listBookRecent);
					LayoutMainScreen.getInstance().mAdapterNewBook
							.notifyDataSetChanged();
					ResourcesManager.ac.waitDialog.hide();
					updateTexts();
				}else{
					ResourcesManager.ac.waitDialog.hide();
				}
			}
			if (!result[1].equals("")) {
				if (sizebookstand < listBookStand.size()) {
					String[] arrUrl = new String[listBookStand.size()
							- sizebookstand];

					for (int i = 0; i < listBookStand.size() - sizebookstand; i++) {
						BookStand aBook = listBookStand.get(i + sizebookstand);
						String ur = aBook.get(BookStand.TAG_FOLDER_IMAGE);
						String foderid = aBook.get(BookStand.TAG_FOLDER_ID);
						if (!" ".equals(foderid) && foderid != null
								&& ur.contains("http:")) {
							arrUrl[i] = ur;
							System.out.println("aaaaaaaa" + ur + "========="
									+ i + " folder id " + foderid);

						}

					}
					ResourcesManager.ac.waitDialog.show();
					DownloadImageService downImage = new DownloadImageService(1);
					downImage.setSizeBookStand(sizebookstand);
					downImage.execute(arrUrl);
					LayoutMainScreen.getInstance().onCreate();
					updateTexts();
				} else if(!isOnline() || !isListBookStand && firtcount2 == 0){
					if (!listBookStand.isEmpty()) {
						listBookStand.clear();
					}
					try {
						XMLProvider.parseStandXml(listBookStand);
					} catch (XmlPullParserException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}					
					LayoutMainScreen.getInstance().mAdapterBookStand
							.setListNewBook(listBookStand);
					LayoutMainScreen.getInstance().mAdapterBookStand
							.notifyDataSetChanged();
					updateTexts();
					ResourcesManager.ac.waitDialog.hide();
				}else{
					ResourcesManager.ac.waitDialog.hide();
				}

			}

			if (!result[2].equals("")) {
				if (listBookInListBookStand.size() > sizeListbookInBookStand) {
					String[] arrUrl = new String[listBookInListBookStand.size()
							- sizeListbookInBookStand];
					for (int i = 0; i < listBookInListBookStand.size()
							- sizeListbookInBookStand; i++) {
						BookRecent aBook = listBookInListBookStand.get(i
								+ sizeListbookInBookStand);
						String ur = aBook.get(BookRecent.TAG_BOOK_COVER);
						String httpepub = aBook.get(BookRecent.TAG_BOOK_URL);
						System.out.println("TAG_BOOK_COVER " + ur);
						System.out.println("TAG_BOOK_URL " + httpepub);
						if (!httpepub.equals("") && httpepub != null
								&& httpepub != null
								&& httpepub.contains("http:")) {
							arrUrl[i] = ur;
						}

					}
					DownloadImageService downImage = new DownloadImageService(2);
					downImage.execute(arrUrl);
					waitDialog.show();
				} else if (listBookInListBookStand.size() == sizeListbookInBookStand) {
					LayoutManager.getInstance().removeView(
							LayoutManager.getInstance().getCurrentView());
					LayoutGridBook.getInstance().show();
					LayoutGridBook.getInstance().list = ResourcesManager.ac.listBookInListBookStand;
					LayoutGridBook.getInstance().onLoadListener();
					ResourcesManager.ac.waitDialog.hide();
				}

			}

			if (!result[3].equals("")) {
			}

			// list boook in category
			if (!result[4].equals("")) {
				ResourcesManager.ac.waitDialog.hide();
				final ArrayList<BookRecent> listCateory = new ArrayList<BookRecent>();
				for (int i = 0; i < listBookInListBookStand.size(); i++) {
					if (!listBookSubCategory.isEmpty()) {
						for (int j = 0; j < listBookSubCategory.size(); j++) {
							System.out.println(listBookInListBookStand.get(i)
									.getId()
									+ "=== "
									+ listBookSubCategory.get(j).getId());
							if (listBookInListBookStand.get(i).getId()
									.equals(listBookSubCategory.get(j).getId())) {
								listCateory.add(listBookInListBookStand.get(i));
								break;
							}
						}
					}
				}
				// notifi

				// TODO Auto-generated method stub
				LayoutManager.getInstance().removeView(
						LayoutManager.getInstance().getCurrentView());
				LayoutGridBook.getInstance().list = listCateory;
				LayoutGridBook.getInstance().onLoadListener();

			}

		}

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (LayoutManager.getInstance().getCurrentLayout() != null)
				LayoutManager.getInstance().getCurrentLayout().onKeyBack();
		}
		return false;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	public RelativeLayout getMainFrameLayout() {
		// TODO Auto-generated method stub
		return rlMain;
	}
}
